/**
 * @description: hrm
 * @date: 2021/8/15
 */

// https://github.com/vitejs/vite/blob/5745a2e8072cb92d647662dc387e7f12b2841cab/packages/vite/src/node/server/ws.ts#L18
const WebSocket = require('ws')
const { logger } = require('../server-utils')

function createWebSocketServer({ port }) {
  let wss = new WebSocket.Server({
    port,
  })

  wss.on('connection', (socket) => {
    logger('ws', 'connection', 'info')
    socket.on('message', function incoming(message) {
      logger('ws received', message, 'info')
    })

    socket.send(JSON.stringify({ type: 'connected' }))
  })

  wss.on('error', (e) => {
    logger('ws', e.message)
  })

  return {
    send(msg = {}) {
      wss.clients.forEach((client) => {
        if (client.readyState === WebSocket.OPEN) {
          client.send(JSON.stringify({ type: 'reload', ...msg }))
        }
      })
    },
  }
}

module.exports = {
  createWebSocketServer,
}
